//
//  TitleSearchViewController.m
//  GoBigMarket
//
//  Created by 王天义 on 16/8/18.
//  Copyright © 2016年 legend. All rights reserved.
//

#import "TitleSearchViewController.h"

#import "AddMapTableViewCell.h"
@interface TitleSearchViewController () <BMKPoiSearchDelegate ,UITextFieldDelegate ,UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate>
{
    UITextField *titleSearch;
    
    UITableView *myTableView;
    NSMutableArray *addressDataArray;
    
    BMKPoiSearch *_searcher; // 重新请求次数
    
    NSString *searchKeyword; //筛选条件字段
    NSInteger repeatNumber;
}
@end

@implementation TitleSearchViewController

//不使用时将delegate设置为 nil
-(void)viewWillDisappear:(BOOL)animated
{
    _searcher.delegate = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    repeatNumber = 0;
    addressDataArray = [NSMutableArray arrayWithCapacity:1];
    
    if ([_searchDic allKeys].count>0) {
        searchKeyword = [NSString stringWithFormat:@"%@", [_searchDic objectForKey:@"name"]];
    }else {
        searchKeyword = @"天安门";
    }
    
    [self loadBackBtnAndSearchBtn];
    [self loadAddressTableView];
    
    [self baiduSearchPOI];
}

#pragma mark - 百度POI检索
- (void)baiduSearchPOI {
    //初始化检索对象
    _searcher =[[BMKPoiSearch alloc]init];
    _searcher.delegate = self;
    //发起检索
    
    BOOL flag;
    
    BMKCitySearchOption *option = [[BMKCitySearchOption alloc] init];
    option.pageCapacity = 50;
    if ([_searchDic allKeys].count>0) {
        option.city = [_searchDic objectForKey:@"city"];
    }else {
        option.city = @"北京";
    }
    option.keyword = searchKeyword;
    flag = [_searcher poiSearchInCity:option];
    
    if(flag)
    {
        NSLog(@"周边检索发送成功");
    }
    else
    {
        NSLog(@"周边检索发送失败");
        repeatNumber++;
        if (repeatNumber<5) {
            [self baiduSearchPOI];
        }
    }
}

//实现PoiSearchDeleage处理回调结果
- (void)onGetPoiResult:(BMKPoiSearch*)searcher result:(BMKPoiResult*)poiResultList errorCode:(BMKSearchErrorCode)error
{
    [addressDataArray removeAllObjects];
    
    if (error == BMK_SEARCH_NO_ERROR) {
        
        //在此处理正常结果
        // 获取坐标周边信息
        for(BMKPoiInfo *poiInfo in poiResultList.poiInfoList)
        {
            NSDictionary *dic = @{@"address":poiInfo.address, @"name":poiInfo.name, @"locationX":[NSString stringWithFormat:@"%f", poiInfo.pt.latitude], @"locationY":[NSString stringWithFormat:@"%f", poiInfo.pt.longitude], @"city":poiInfo.city};
            [addressDataArray addObject:dic];
        }
    } else if (error == BMK_SEARCH_AMBIGUOUS_KEYWORD){
        //当在设置城市未找到结果，但在其他城市找到结果时，回调建议检索城市列表
        // result.cityList;
        NSLog(@"起始点有歧义");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"抱歉，在当前城市未找到结果!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    } else {
        NSLog(@"抱歉，未找到结果");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"抱歉，未找到结果!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    
    [myTableView reloadData];
    if (addressDataArray.count>0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [myTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
    }
    
}


#pragma mark - 返回按钮，并做数据回调处理
- (void)loadBackBtnAndSearchBtn {
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 40, 30);
    [leftBtn setImage:[UIImage imageNamed:@"jiantou2"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    
    titleSearch = [[UITextField alloc] initWithFrame:CGRectMake(20, 5, kScrernWidth-30, 30)];
    titleSearch.backgroundColor = [UIColor colorWithRed:235/255.0 green:236/255.0 blue:241/255.0 alpha:1];
    titleSearch.placeholder = @"查找小区/大厦/学校等";
    titleSearch.font = [UIFont systemFontOfSize:14];
    titleSearch.clearButtonMode = UITextFieldViewModeAlways;
    titleSearch.clearsOnBeginEditing = YES;
    titleSearch.layer.cornerRadius = 5;
    titleSearch.layer.masksToBounds = YES;
    titleSearch.layer.borderWidth = 0.5;
    titleSearch.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 25, 30)];
    UIImageView *sousuoImage = [[UIImageView alloc] initWithFrame:CGRectMake(5, 7, 16, 16)];
    sousuoImage.image = [UIImage imageNamed:@"shouye_sousuo"];
    [leftView addSubview:sousuoImage];
    titleSearch.leftViewMode = UITextFieldViewModeAlways;
    titleSearch.leftView = leftView;
    titleSearch.delegate = self;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewEditChanged:) name:UITextFieldTextDidChangeNotification object:titleSearch];
    self.navigationItem.titleView = titleSearch;
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(0, 0, 40, 30);
    [rightBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(baiduSearchPOI) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
}

- (void)back {
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark 地图底部tableView数据展示
- (void)loadAddressTableView {
    myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScrernWidth, kScrernHeight) style:UITableViewStylePlain];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
}

// tableviewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (addressDataArray.count>0) {
        tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    }else {
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    
    return addressDataArray.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"cellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:identifier];
    }
    
    if (indexPath.row == 0 && [_searchDic allKeys].count>0) {
        static NSString *cellIdentifier = @"cellinden";
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(17 , 15, 15, 20)];
        imageView.image = [UIImage imageNamed:@"icon_baidu_marker"];
        [cell addSubview:imageView];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, kScrernWidth - 60, 50)];
        label.text = [NSString stringWithFormat:@"%@(%@)", [addressDataArray[indexPath.row] objectForKey:@"address"], [addressDataArray[indexPath.row] objectForKey:@"name"]];
        [cell addSubview:label];
        
        return cell;
    }
    cell.textLabel.text = [addressDataArray[indexPath.row] objectForKey:@"name"];
    cell.detailTextLabel.text = [addressDataArray[indexPath.row] objectForKey:@"address"];
    cell.detailTextLabel.textColor = [UIColor lightGrayColor];
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = addressDataArray[indexPath.row];
    [self.navigationController popViewControllerAnimated:NO];
    self.titleSearchBlock(dic);
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [titleSearch resignFirstResponder];
    
}
#pragma mark - textFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (![textField.text isEqualToString:@""]) {
        searchKeyword = textField.text;
        [self baiduSearchPOI];
    }
    [titleSearch resignFirstResponder];
    return YES;
}

// 监听文本改变
-(void)textViewEditChanged:(NSNotification *)obj{
    
    UITextField *textField = (UITextField *)obj.object;
    
    UITextRange *selectedRange = [textField markedTextRange];
    //获取高亮部分
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position) {
        if (![textField.text isEqualToString:@""]) {
            searchKeyword = textField.text;
            [self baiduSearchPOI];
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

